import fetch from 'node-fetch';

const LINK = 'https://ghfast.top/https://github.com/devil233-ui/resources/raw/master/resources/json/mihoyo/';

const RERUN_QUERY_REGEX = /^([#*%])?((gs|原神)|(sr|(星|崩)铁|星穹铁道)|(zzz|绝区零))卡池多久未复刻$/
const HISTORY_QUERY_REGEX = /^[#*%](.*)卡池记录$/

const GAME_TYPES = {
    'gs': { name: ['原神', 'gs'], type: '祈愿', file: 'gs卡池记录.json', reg: '#' },
    'sr': { name: ['星穹铁道', 'sr', '星铁', '崩铁'], type: '跃迁', file: 'sr卡池记录.json', reg: '*' },
    'zzz': { name: ['绝区零', 'zzz'], type: '调频', file: 'zzz卡池记录.json', reg: '%' }
};

export class CardPoolQuery extends plugin {
    constructor() {
        super({
            name: "卡池查询",
            dsc: "查询游戏卡池信息",
            event: "message",
            priority: 1,
            rule: [
                { reg: RERUN_QUERY_REGEX, fnc: 'queryLastRerun' },
                { reg: HISTORY_QUERY_REGEX, fnc: 'queryCardPoolHistory' }
            ]
        });
    }

    async queryLastRerun(e) {
        const queryType = e.msg.replace(/#|\/|\*|%|卡池多久未复刻/g, '');
        const gameInfo = Object.values(GAME_TYPES).find(game =>
            game.name.includes(queryType) || game.type.includes(queryType));

        if (!gameInfo) return e.reply('未知的游戏类型');

        const linkData = await this.fetchData(gameInfo.file);
        const otherRoles = linkData.OtherRoles.filter(role =>
            !linkData.CurrentRole.includes(role.name));

        if (otherRoles.length === 0)
            return e.reply(`${linkData.CurrentRole}卡池结束后可查看`);

        const result = this.calculateRerunInterval(otherRoles);

        return e.reply(`当前${gameInfo.type}: ${linkData.CurrentRole}\r${result.join('\r')}`)
    }

    async queryCardPoolHistory(e) {
        const queryRole = e.msg.replace(/卡池记录/g, '').replace(/#星铁/g, '*').replace(/#绝区零/g, '%');
        const gameType = queryRole[0];
        const gameInfo = Object.values(GAME_TYPES).find(game => game.reg.startsWith(gameType));

        if (!gameInfo) return e.reply('未知的游戏类型');

        const linkData = await this.fetchData(gameInfo.file);
        const roleData = linkData.OtherRoles.find(role =>
            role.name === queryRole.replace(/#|\/|\*|%/g, ''));

        if (!roleData) return e.reply('未查询到该角色卡池信息');

        const cardPoolRecords = roleData.Record.map((data, index) => {
            const version = Number.isInteger(data.Version) ? `${data.Version}.0` : data.Version;
            const upOrDown = data.UpOrDown === '中间' ? data.UpOrDown : `${data.UpOrDown}半`;
            return `第${index + 1}次${gameInfo.type} ${version} ${upOrDown}\r开始时间: ${data.StartTime}\r结束时间: ${data.EndTime}\r`;
        });

        return e.reply(`${roleData.name}卡池记录\r${cardPoolRecords.join('\r').trim()}`)
    }

    async fetchData(filename) {
        return (await fetch(LINK + filename)).json();
    }

    calculateRerunInterval(data) {
        const today = new Date();
        const results = data.map(role => {
            const lastRecord = role.Record[role.Record.length - 1];
            const timeDiff = today - new Date(lastRecord.EndTime);
            const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            return { name: role.name, days: days };
        });

        results.sort((a, b) => b.days - a.days);

        return results.map(result =>
            `${result.name} 已 [${result.days.toString().padStart(3, '0')}]天未复刻`
        );
    }
}